# from django.shortcuts import render
import json
import uuid
from rest_framework import viewsets
from .models import Report, RepModel
from .serializers import ReportSerializer
from reportservice.helpers import ApiResponse, create_directories_if_not_exist
from docxtpl import DocxTemplate, InlineImage
from jinja2 import Environment
import subprocess
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from oss_service.views import bucket, digital_bucket
import os
from datetime import datetime
import qrcode
import time
from docx.shared import Mm
import requests
from dingtalk_service.yida_client import YidaClient
from docx import Document
from docx.shared import Inches
from .utils import merge_pdfs, get_report_code_inpdf
from django.conf import settings
from datetime import datetime, timezone, timedelta
import fitz
import threading
from fitz import FileDataError
from urllib.parse import quote
from io import BytesIO
from django.shortcuts import redirect, render


# base_path = r"/root/xm-detection-service/data"
base_path = os.path.join(settings.BASE_DIR, r'data')
create_directories_if_not_exist([
    rf"{base_path}/xiaming_tmp/model_docs",
    f"{base_path}/xiaming_tmp/tmp_img",
    f"{base_path}/xiaming_tmp/print_tmp/",
    f"{base_path}/xiaming_tmp/tmp_file/"
])
tmp_path = rf"{base_path}/xiaming_tmp"
admin_user_id = "301546025724261514"


class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = ReportSerializer
# Create your views here.


# 生成pdf

def convert_to_pdf(input_file_path, output_dir, oss_path):
    print("正在生成pdf")
    # LibreOffice 命令行
    cmd = [
        "soffice",
        "--headless",
        "--convert-to",
        "pdf",
        "--outdir",
        output_dir,
        input_file_path
    ]
    subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # bucket.put_object_from_file(rf"{oss_path}/cover.pdf", rf"{output_dir}/cover.pdf")
    return oss_path


def convert_to_pdf_to_oss(input_file_path, output_dir, oss_path, filename):
    print("正在生成pdf")
    # LibreOffice 命令行
    cmd = [
        "soffice",
        "--headless",
        "--convert-to",
        "pdf",
        "--outdir",
        output_dir,
        rf"{input_file_path}/{filename}.docx"
    ]
    subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    bucket.put_object_from_file(
        rf"{oss_path}/{filename}.pdf", rf"{output_dir}/{filename}.pdf")
    return oss_path

# 生成二维码图片


def genQrCode(qr_text):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(qr_text)  # 这里填写你想转换成二维码的文本
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    tmp_url = rf"{base_path}/xiaming_tmp/tmp_img/{int(time.time())}.png"
    img.save(tmp_url)
    return tmp_url

# 解析模板json


def compile_tpl_data(tpl: DocxTemplate, datasource: dict):
    renderData = {}
    for key, value in datasource.items():
        if isinstance(value, str):
            try:
                json_value = json.loads(value)
                tmp_value = compile_tpl_data(tpl, {key: json_value})
                renderData[key] = tmp_value[key]
            except:
                renderData[key] = value
            continue
        if isinstance(value, list):
            clist = []
            for item in value:
                sub_opt = {
                    key: item
                }
                clist.append(compile_tpl_data(tpl, sub_opt))
                renderData[key] = clist
            continue
        if isinstance(value, (int, float)):
            renderData[key] = str(value)
        if isinstance(value, dict):
            if 'type' not in value:
                return compile_tpl_data(tpl, value)
            if value["type"] == "qrcode":
                url = genQrCode(value["text"])
                renderData[key] = InlineImage(tpl,
                                              image_descriptor=url, width=Mm(value["width"]))
            elif value["type"] == "img":
                renderData[key] = InlineImage(tpl,
                                              image_descriptor=value["url"], width=Mm(value["width"]))
            elif value["type"] == "date":
                timestamp = int(value["value"]) / 1000
                dt_object_utc = datetime.fromtimestamp(
                    timestamp, tz=timezone.utc)
                timezone_offset = 8  # Change this as per your local timezone
                local_timezone = timezone(timedelta(hours=timezone_offset))
                dt_object_local = dt_object_utc.astimezone(local_timezone)
                renderData[key] = dt_object_local.strftime(value["format"])
            continue
    return renderData


def download_sign(sign_url):
    second_sign_res = requests.get(sign_url)
    if second_sign_res.status_code == 200:
        second_sign_img = second_sign_res.content
        sign_url = rf"{tmp_path}/tmp_img/{uuid.uuid4()}.png"
        with open(sign_url, "wb") as f:
            f.write(second_sign_img)
    return sign_url


# 根据user_id获取人员信息
def get_user_by_yida_user_id(user_id: str, admin_user: str, report_code):
    user_form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
    userinfo = YidaClient.get_form_data_by_search_field(form_uuid=user_form_uuid, userId=admin_user if admin_user else user_id, search_field={
        "textField_lp0zbal4": user_id,
    })
    user = {}
    if (userinfo):
        userinfo = userinfo[0].form_data
        user["name"] = userinfo["textField_lp0tv654"]
        if "radioField_lqdk47dg" in userinfo:
            if (userinfo["radioField_lqdk47dg"] == "电子签名"):
                if "digitalSignatureField_lp0tv65b" in userinfo:
                    user["sign_arr"] = userinfo["digitalSignatureField_lp0tv65b"]
            elif (userinfo["radioField_lqdk47dg"] == "钉钉签名"):
                # 获取该流程下用户的签名
                qm_form_uuid = "FORM-36CB6E26E47043A4ADAE0C923F7E730DEW85"
                qminfo = YidaClient.get_form_data_by_search_field(form_uuid=qm_form_uuid, userId=admin_user if admin_user else user_id, search_field={
                    "textField_lqvmzy2z": report_code,
                    "textField_lqvmzy30": user_id
                })
                if (qminfo):
                    qminfo = qminfo[0].form_data
                    if "digitalSignatureField_lqvmzy35" in qminfo:
                        user["sign_arr"] = qminfo["digitalSignatureField_lqvmzy35"]
            return user, userinfo["radioField_lqdk47dg"]
        else:
            return None, None


# 初步生成报告
@csrf_exempt
@require_http_methods(["POST"])
def generateBaseReport(request, uuid_string):
    try:
        report_model = RepModel.objects.get(uuid=uuid_string)
    except RepModel.DoesNotExist:
        return ApiResponse.fail(message="未找到模板.")
    datasource: dict[str, any] = json.loads(request.body)
    form_uuid = datasource["formUuid"]
    user_id = json.loads(datasource["userId"])
    report_code = datasource["报告编号"]
    form_inst_id = datasource["formInstId"]  # 获取数据源中的表单实例ID
    res = YidaClient.get_form_items_by_ids(form_uuid, form_inst_id, user_id[0])
    form_data = res[0].form_data
    if ("检测人1" in datasource):
        if ("-" in datasource["检测人1"]):
            jcr1_id = datasource["检测人1"].split("-")[1]
        else:
            jcr1_id = datasource["检测人1"]
        if (jcr1_id):
            jcr1, _ = get_user_by_yida_user_id(
                jcr1_id, user_id[0], report_code)
            datasource["检测人1"] = jcr1['name']
    if ("检测人2" in datasource):
        if ("-" in datasource["检测人2"]):
            jcr2_id = datasource["检测人2"].split("-")[1]
        else:
            jcr2_id = datasource["检测人2"]
        if (jcr2_id):
            jcr2, _ = get_user_by_yida_user_id(
                jcr2_id, user_id[0], report_code)
            datasource["检测人2"] = jcr2['name']
    if ("审核人" in datasource):
        if ("-" in datasource["审核人"]):
            shr_id = datasource["审核人"].split("-")[1]
        else:
            shr_id = datasource["审核人"]
        if (shr_id):
            shr, sign_method = get_user_by_yida_user_id(
                shr_id, user_id[0], report_code)
            if (sign_method == "钉钉签名"):
                if "digitalSignatureField_lqrz4eha" in form_data:
                    shr["sign_arr"] = form_data["digitalSignatureField_lqrz4eha"]
            datasource["审核人"] = shr['name']
    if ("批准人" in datasource):
        if ("-" in datasource["批准人"]):
            pzr_id = datasource["批准人"].split("-")[1]
        else:
            pzr_id = datasource["批准人"]
        if (pzr_id):
            pzr, sign_method = get_user_by_yida_user_id(
                pzr_id, user_id[0], report_code)
            if (sign_method == "钉钉签名"):
                if "digitalSignatureField_lqdi3j6t" in form_data:
                    pzr["sign_arr"] = form_data["digitalSignatureField_lqdi3j6t"]
            datasource["批准人"] = pzr['name']
    if ("组长" in datasource):
        if ("-" in datasource["组长"]):
            group_leader_id = datasource["组长"].split("-")[1]
        else:
            group_leader_id = datasource["组长"]
        if (group_leader_id):
            group_leader, _ = get_user_by_yida_user_id(
                group_leader_id, user_id[0], report_code)
            datasource["组长"] = group_leader['name']
    if ("组员一" in datasource):
        if ("-" in datasource["组员一"]):
            group_user1_id = datasource["组员一"].split("-")[1]
        else:
            group_user1_id = datasource["组员一"]
        if (group_user1_id):
            group_user1, _ = get_user_by_yida_user_id(
                group_user1_id, user_id[0], report_code)
            datasource["组员一"] = group_user1['name']
    if ("组员二" in datasource):
        if ("-" in datasource["组员二"]):
            group_user2_id = datasource["组员二"].split("-")[1]
        else:
            group_user2_id = datasource["组员二"]
        if (group_user2_id):
            group_user2, _ = get_user_by_yida_user_id(
                group_user2_id, user_id[0], report_code)
            datasource["组员二"] = group_user2['name']

    urlstr = form_data['attachmentField_lqrz4ehj']  # 获取上传的报告主体文件
    file_down = json.loads(urlstr)[0]["downloadUrl"]
    full_download_url = YidaClient.get_full_download_url(
        user_id=user_id[0], download_url=file_down)
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        file_content = response.content
        try:
            report = Report.objects.get(report_code=report_code)
        except:
            report = Report(report_code=datasource["报告编号"],
                            model_id=report_model.id)
            report.report_path = rf"out-pdf/{datetime.now().strftime('%Y%m')}/{report.uuid}"
        # 获取报告页数

        bucket.put_object(rf"{report.report_path}/content.pdf", file_content)
        create_directories_if_not_exist(
            [rf"{tmp_path}/{report.report_path}"])  # 创建报告缓存路径
        content_path = rf"{tmp_path}/{report.report_path}/content.pdf"
        print(f"pdf 地址>>>>>{content_path}")
        with open(content_path, 'wb') as out:
            out.write(file_content)
        try:
            with fitz.open(content_path) as doc_pdf:
                # 返回PDF的页数
                total_page = len(doc_pdf)
                datasource["全部页码"] = total_page + 1
            print(f"报告内容上传成功")
        except FileDataError:
            print("文件损坏或格式错误")
            return ApiResponse.fail(message="文件损坏或格式错误")
    try:
        tmp_file_path = rf"{tmp_path}/{report_model.path}"
        if not os.path.exists(tmp_file_path):
            print(f"缓存模板不存在，从oss下载>>>>>>>")
            create_directories_if_not_exist([tmp_file_path])
            if bucket.object_exists(report_model.path):
                print("文件已找到>>>>>>")
            bucket.get_object_to_file(report_model.path, tmp_file_path)
            print(f"模板下载成功>>>>>>>")
        else:
            print(f"本地模板文件已找到{tmp_file_path}")
        try:
            if "sign_arr" in jcr1:
                datasource["检测人签名1"] = {
                    "type": "img",
                    "url": download_sign(jcr1["sign_arr"]),
                    "width": 30
                }
        except:
            print("检测人签名1不存在")
        try:
            if jcr2 and "sign_arr" in jcr2:
                datasource["检测人签名2"] = {
                    "type": "img",
                    "url": download_sign(jcr2["sign_arr"]),
                    "width": 30
                }
        except:
            print("检测人签名2不存在")
        try:
            if shr and "sign_arr" in shr:
                datasource["审核人签名"] = {
                    "type": "img",
                    "url": download_sign(shr["sign_arr"]),
                    "width": 30
                }
        except:
            print("审核人签名不存在")
        try:
            if pzr and "sign_arr" in pzr:
                datasource["批准人签名"] = {
                    "type": "img",
                    "url": download_sign(pzr["sign_arr"]),
                    "width": 30
                }
        except:
            print("批准人签名不存在")
        try:
            if group_leader and "sign_arr" in group_leader:
                datasource["组长签名"] = {
                    "type": "img",
                    "url": download_sign(group_leader["sign_arr"]),
                    "width": 30
                }
        except:
            print("组长签名不存在")
        try:
            if group_user1 and "sign_arr" in group_user1:
                datasource["组员一"] = {
                    "type": "img",
                    "url": download_sign(group_user1["sign_arr"]),
                    "width": 30
                }
        except:
            print("组员一签名不存在")
        try:
            if group_user2 and "sign_arr" in group_user2:
                datasource["组员二"] = {
                    "type": "img",
                    "url": download_sign(group_user2["sign_arr"]),
                    "width": 30
                }
        except:
            print("组员二签名不存在")

        def generateReportPdf():
            doc = DocxTemplate(tmp_file_path)
            renderData = compile_tpl_data(doc, datasource)
            doc.render(renderData)
            outdocpath = f"{tmp_path}/{report.report_path}/cover.docx"
            doc.save(outdocpath)
            bucket.put_object_from_file(
                rf"{report.report_path}/cover.docx", outdocpath)
            tmpPdfpath = f"{tmp_path}/{report.report_path}"
            convert_to_pdf(
                outdocpath, tmpPdfpath, report.report_path)
            # 合成pdf
            merge_pdfs([rf"{tmp_path}/{report.report_path}/cover.pdf",
                        rf"{tmp_path}/{report.report_path}/content.pdf"], rf"{tmp_path}/{report.report_path}/whole.pdf")
            print(f"正在保存完整报告>>>>>>>")
            bucket.put_object_from_file(
                rf"{report.report_path}/whole.pdf", rf"{tmp_path}/{report.report_path}/whole.pdf")
            report.completed_at = datetime.now()
            report.digital_sign_order_no = None
            report.save()
        thread = threading.Thread(target=generateReportPdf)
        thread.start()
        print(f"报告生成中>>>  >>>>")
        return ApiResponse.success(message=f"报告{report_code}数据已导入,正在生成报告，请稍后")
    except Report.DoesNotExist:
        return ApiResponse.fail(message="No record found with the provided UUID.", code=404)

    except ValueError:
        return ApiResponse.fail(message="Invalid UUID format.")
    except Exception:
        return ApiResponse.fail(message=f"报告生成失败")


@csrf_exempt
@require_http_methods(["GET"])
# 查找报告封面
def getCoverPdf(request):
    report_code = request.GET.get('reportCode')
    report = Report.objects.get(report_code=report_code)
    path = rf"{report.report_path}/cover.pdf"
    # 创建限速下载文件的签名URL, 有效期60s。
    params = {'response-content-disposition': 'inline'}
    url = bucket.sign_url('GET', path, 3600, params=params)
    return ApiResponse.success(message=rf"报告已生成，点击下载：{url}", data=url)


@csrf_exempt
@require_http_methods(["GET"])
# 查找报告内容
def getContentPdf(request):
    report_code = request.GET.get('reportCode')
    report = Report.objects.get(report_code=report_code)
    path = rf"{report.report_path}/cover.pdf"
    # 创建限速下载文件的签名URL, 有效期3600s。
    params = {'response-content-disposition': 'inline'}
    url = bucket.sign_url('GET', path, 3600, params=params)
    return ApiResponse.success(message=rf"报告已生成", data=url)


@csrf_exempt
@require_http_methods(["GET"])
# 返回完整报告内容
def getWholePdf(request):
    report_code = request.GET.get('reportCode')
    report = Report.objects.get(report_code=report_code)
    signed_path = rf"{report.report_path}/signed.pdf"
    path = rf"{report.report_path}/whole.pdf"
    path_bak = rf"{report.report_path}/whole_print.pdf"
    # 创建限速下载文件的签名URL, 有效期60s。
    params = {'response-content-disposition': 'inline'}
    if (bucket.object_exists(signed_path)):
        url = bucket.sign_url('GET', signed_path, 3600, params=params)
        return ApiResponse.success(message=rf"报告已找到", data=url)
    elif (bucket.object_exists(path)):
        url = bucket.sign_url('GET', path, 3600, params=params)
        return ApiResponse.success(message=rf"报告已找到", data=url)
    elif (bucket.object_exists(path_bak)):
        url = bucket.sign_url('GET', path_bak, 3600, params=params)
        return ApiResponse.success(message=rf"报告已找到", data=url)
    else:
        return ApiResponse.fail(message=rf"报告未找到")


@csrf_exempt
@require_http_methods(["GET"])
def getWholeReport(request):
    report_code = request.GET.get('reportCode')
    report = Report.objects.get(report_code=report_code)
    path = report.report_path
    # 创建限速下载文件的签名URL, 有效期60s。
    params = {'response-content-disposition': 'inline'}
    url = bucket.sign_url('GET', path, 3600, params=params)
    return ApiResponse.success(message=rf"报告已生成，点击下载：{url}", data=url)


# 上传模版


@csrf_exempt
@require_http_methods(["POST"])
def uploadModel(request):
    try:
        file = request.FILES["file"]
        name = request.POST.get("name")
        company = request.POST.get("company")
        repModel = RepModel(name=name, company=company)
        repModel.path = rf"model_docs/{repModel.uuid}.docx"
        print(f"uuid>>>>>>{repModel.uuid}")
        bucket.put_object(rf"model_docs/{repModel.uuid}.docx", file)
        repModel.save()
        return ApiResponse.success(message=f"模板上传成功，模板号为{repModel.uuid}", data=repModel.uuid)
    except ValueError:
        return ApiResponse.fail(message="Invalid value")


@csrf_exempt
@require_http_methods(["POST"])
def uploadModelByYida(request):

    print(f"request is {request.body}")
    datasource: dict[str, any] = json.loads(request.body)
    user_id_json_str = datasource['userId']
    form_uuid = datasource["formUuid"]
    user_ids = json.loads(user_id_json_str)
    res = YidaClient.get_form_items_by_ids(
        form_uuid=form_uuid, form_inst_id=datasource["formInstId"], userId=user_ids[0])
    print(f"res is {res}")
    form_data = res[0].form_data
    name = form_data["textField_lq966fhp"]
    company = datasource["company"]
    yidaUUid = form_data['textField_lq966fhr']
    fileStr = form_data['attachmentField_lq966fhq']
    file_download = json.loads(fileStr)[0]["downloadUrl"]
    print(f"download>>>>>{file_download}")
    full_download_url = YidaClient.get_full_download_url(
        user_id=user_ids[0], download_url=file_download)
    url = full_download_url.body.result
    response = requests.get(url)
    if response.status_code == 200:
        file_content = response.content
    try:
        repModel = RepModel(uuid=yidaUUid, name=name, company=company)
        repModel.path = rf"model_docs/{repModel.uuid}.docx"
        print(f"uuid>>>>>>{repModel.uuid}")
        bucket.put_object(rf"model_docs/{repModel.uuid}.docx", file_content)
        repModel.save()
        return ApiResponse.success(message=f"模板上传成功，模板号为{repModel.uuid}", data=repModel.uuid)
    except ValueError:
        return ApiResponse.fail(message="Invalid value")

# 打印财务清单


@csrf_exempt
@require_http_methods(["POST"])
def print_by_model(request, uuid_string):
    tmp_path = rf"{base_path}/xiaming_tmp"
    try:
        report_model = RepModel.objects.get(uuid=uuid_string)
    except RepModel.DoesNotExist:
        return ApiResponse.fail(message="未找到模板.")

    datasource: dict[str, any] = json.loads(request.body)
    try:
        tmp_file_path = rf"{tmp_path}/{report_model.path}"
        if not os.path.exists(tmp_file_path):
            create_directories_if_not_exist([tmp_file_path])
            print(f"缓存模板不存在，从oss下载>>>>>>>")
            if bucket.object_exists(report_model.path):
                print("文件已找到>>>>>>")
            bucket.get_object_to_file(report_model.path, tmp_file_path)
            print(f"模板下载成功>>>>>>>")
        else:
            print(f"本地模板文件已找到{tmp_file_path}")
        doc = DocxTemplate(tmp_file_path)
        renderData = compile_tpl_data(doc, datasource)
        doc.render(renderData)
        print_oss_path = rf"print_tmp/{datetime.now().strftime('%Y%m')}/{uuid.uuid4()}"
        print_path = f"{tmp_path}/{print_oss_path}"
        filename = "print"
        create_directories_if_not_exist([print_path])
        doc.save(rf"{print_path}/{filename}.docx")
        convert_to_pdf_to_oss(
            print_path, print_path, print_oss_path, filename)
        url_report = bucket.sign_url('GET', rf"{print_oss_path}/{filename}.pdf", 600, params={
                                     'response-content-disposition': 'inline', 'Content-Type': 'application/pdf'})
        return ApiResponse.success(message="打印成功.", data=url_report)
    except:
        return ApiResponse.fail(message="模版转换出错.")

# 测试打印模版


@csrf_exempt
@require_http_methods(["POST"])
def test_render(request, uuid_string):
    datasource: dict[str, any] = json.loads(request.body)
    model_path = rf"{base_path}/xiaming_tmp/model_docs/{uuid_string}.docx"
    doc = DocxTemplate(model_path)
    renderData = compile_tpl_data(doc, datasource)
    doc.render(renderData)
    outdocpath = f"{base_path}/xiaming_tmp/test_tmp/cover.docx"
    doc.save(outdocpath)
    pass


@csrf_exempt
@require_http_methods(["GET"])
def get_user_id_by_tel(request):
    tel = request.GET.get("tel")
    form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
    userinfo = YidaClient.get_form_data_by_search_field(
        form_uuid=form_uuid, userId="301546025724261514", search_field={"textField_lp0tv655": tel})
    user = {}
    if (userinfo):
        userinfo = userinfo[0].form_data
        user["tel"] = userinfo["textField_lp0tv655"]
        if (user["tel"].endswith(tel)):
            return ApiResponse.success(data=userinfo["textField_lp0zbal4"])
        else:
            return ApiResponse.fail(message="查无此人")


@csrf_exempt
@require_http_methods(["GET"])
def bind_user_tel(request):
    tel = request.GET.get("tel")
    name = request.GET.get("name")
    form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
    user_id = "301546025724261514"
    userinfo = YidaClient.get_ids_by_search_field(
        form_uuid=form_uuid, userId=user_id, search_field={"textField_lp0tv654": name})
    user_form_inst_id = userinfo[0]
    update_res = YidaClient.update_form_data_by_id(
        form_uuid=form_uuid, userId=user_id, form_inst_id=user_form_inst_id, update_field={"textField_lp0tv655": tel})
    if (update_res == "success"):
        return ApiResponse.success(message="绑定成功")
    else:
        return ApiResponse.fail(message="绑定失败")
    

@csrf_exempt
@require_http_methods(["GET"])
def get_report_detail(request):
    report_code = request.GET.get("report_code")
    res_data = YidaClient.get_form_data_by_search_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",admin_user_id,
                                             [
                                              {
                                                "type": "TEXT",
                                                "operator": "eq",
                                                "componentName": "TextField",
                                                "key": "textField_lp93kxup",
                                                "value": report_code
                                              }
                                            ])
    return ApiResponse.success(data=res_data[0].form_data)

@csrf_exempt
@require_http_methods(["GET"])
def compare_report_code(request):
    downloadUrl = request.GET.get("downloadUrl")
    name = request.GET.get("name")
    ext = name.split(".")[-1]
    if not downloadUrl:
        return ApiResponse.fail(message="下载链接获取失败")
    report_code: str = request.GET.get("reportCode")
    admin_user_id = "301546025724261514"
    full_download_url = YidaClient.get_full_download_url(
        user_id=admin_user_id, download_url=downloadUrl)
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        pdf_content = BytesIO(response.content)
        try:
            if ext == "pdf":
                report_code_pdf = get_report_code_inpdf(pdf_content=pdf_content)
                if report_code_pdf == report_code or report_code.startswith("XLY"):
                    return ApiResponse.success(message="报告编号比对正确")
                else:  
                    return ApiResponse.fail(message="报告编号比对有误，请仔细检查")
            elif ext == "docx":
                doc = Document(pdf_content)
                # 遍历每个节的页眉
                for section in doc.sections:
                    header = section.header
                    # 遍历页眉中的每个段落
                    for paragraph in header.paragraphs:
                        if report_code in paragraph.text or report_code.startswith("XLY"):
                            return ApiResponse.success(message="报告编号比对正确")
                return ApiResponse.fail(message="报告编号比对有误，请仔细检查")
        except:
            return ApiResponse.fail(message="报告编号获取有误，请仔细检查")



@csrf_exempt
@require_http_methods(["POST"])
def create_digital_sign_order(request):
    datasource: dict[str, any] = json.loads(request.body)
    report_code = datasource["report_code"]
    participants_p = datasource["participants_p"]
    participants_e = datasource["participants_e"]
    model_uuid = datasource["model_uuid"]
    report_model = YidaClient.get_form_data_by_search_field(
        "FORM-D4C9AA2AA5634D7CB46142B94F6B8441IA1U", admin_user_id, {"textField_lq966fhr": model_uuid})
    participants_personal = []
    # 公章区域数据列表
    official_seal_area_list = []
    if report_model:
        sign_areas = report_model[0].form_data['tableField_ls9optr6']
        for index, sign_area in enumerate(sign_areas):
            if len(participants_p) <= index:
                continue
        #个人章
            participants_personal.append({
                "userType": "2",
                "dingtalkUserId": participants_p[index],
                "coordinate": rf'[{{"lby":{centimeter_transformation_point(sign_area["numberField_ls9optra"])},"lbx":{centimeter_transformation_point(sign_area["numberField_ls9optr9"])},"rty":{centimeter_transformation_point(sign_area["numberField_ls9optra"]) + centimeter_transformation_point(sign_area["numberField_ls9optro"])},"rtx":{centimeter_transformation_point(sign_area["numberField_ls9optr9"]) + centimeter_transformation_point(sign_area["numberField_ls9optro"])},"page":{sign_area["numberField_ls9optr7"]}}}]'
            })
        # 公章区域 ------------
        official_seal_areas = report_model[0].form_data['tableField_lt8ndw9l']
        
        for index, official_seal_area in enumerate(official_seal_areas):
            seal = json.loads(json.loads(official_seal_area.get("associationFormField_lvdgd8ot_id")))[0]
            matching_items = [item for item in official_seal_area_list if item.get("sealFileUuid") == seal.get("subTitle")]
            if matching_items:
                official_coordinate = matching_items[0].get("coordinate_list")
            else:
                official_seal_info = {
                    "userType": "2",
                    "dingtalkUserId": participants_e[0],
                    "sealFileUuid": seal.get("subTitle"),
                    "coordinate":"",
                    "coordinate_list":[],
                    "enterpriseCardno":"93k12jadfas01231203",
                    "coordinateRiding":f"{centimeter_transformation_point(official_seal_area['numberField_ls9optrm'])}F,{centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m'])}F" if official_seal_area.get("numberField_ls9optrm") else None
                    # "coordinateRiding":"200.0F, 350.0F"
                }
                official_seal_area_list.append(official_seal_info)
                official_coordinate = official_seal_info.get("coordinate_list")
            coordinate_item = {
                'lbx': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9o']),
                'lby': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9n']),
                'rtx': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9o']) + centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m']),
                'rty': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9n']) + centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m']),
                'page': official_seal_area['numberField_lt8ndw9p']
            }
            official_coordinate.append(coordinate_item)
        for seal_e in official_seal_area_list:
            seal_e["coordinate"] = json.dumps(seal_e["coordinate_list"])
        #企业章
        
        # 公章区域 ------------
    # print(official_seal_area_list)
    # return 
    try:
        report = Report.objects.get(report_code=report_code)
    except Exception as err:
        return ApiResponse.fail(message="未找到报告")
    now = datetime.now()
    formatted_now = now.strftime("%Y%m")
    url = f'https://api.zjcxjc.cn/api/v1/digital-sign/create-order'
    data = {
        "participants": [],
        "callbackUrl":"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/sign-order-completed"
    }
    # data["participants"].extend(
    #     [{"userType": "1", "userId": x} for x in participants_e])
    data["participants"].extend(participants_personal)
    data["participants"].extend(official_seal_area_list)
    # data["participants"].extend(
    #     [{"userType": "2", "dingtalkUserId": x, "coordinate": r"[{lby:200,lbx:200,rty:300,rtx:300,page:1}]"} for x in participants_p])
    response = requests.post(url, json=data)
    print(data["participants"])
    if response.status_code == 200:
        
        res = response.json()
        print(res)
        if (res["code"] == 200):
            digital_bucket.copy_object(
                "xu-bk-chengxiang", f"{report.report_path}/whole.pdf", res['data']['contractFilePath']+'origin.pdf')
            ds_no = res["data"]["orderNum"]
            print('-',ds_no)
            report.digital_sign_order_no = ds_no
            report.save()
            # 创建一份伪签名文档
            # threading.Thread(target=create_fake_sign_order, args=(report.report_path,)).start()
            return ApiResponse.success(message="订单创建成功", data=ds_no)
        return ApiResponse.fail(message="订单创建失败>>>")
    else:
        # 处理错误情况
        return ApiResponse.fail(message="订单创建失败")


@csrf_exempt
@require_http_methods(["GET"])
def view_signed_file(request):
    order_no = request.GET.get("orderNo")
    url = f'https://api.zjcxjc.cn/api/v1/digital-sign/view-origin-file?orderNo={order_no}'
    response = requests.get(url)
    if response.status_code == 200:
        res = response.json()
        if (res["code"] == 200):
            return redirect(res["data"])
    return ApiResponse.fail(message="未找到文件")

def face_success(request):
    signRecordId = request.GET.get("signRecordId")
    print('signRecordId',signRecordId)
    context = {
        'message': "World!",
        'signRecordId': signRecordId
    }
    return render(request, 'success.html',context)


# 厘米转化为点（单位转化）
def centimeter_transformation_point(value):
    # 尝试转换输入值
    if isinstance(value, str):  # 检查value是否为字符串
        try:
            # 尝试将字符串转为浮点数
            number = float(value)
        except ValueError:
            # 如果转换失败，使用0代替
            number = 0
    elif isinstance(value, (int, float)):  # 检查value是否为整数或浮点数
        number = value
    else:
        # 如果传入的不是字符串、整数或浮点数，也使用0代替
        number = 0
    
    # 将得到的数字乘以28.35
    result = round(number * 28.35, 2)
    return result



@csrf_exempt
@require_http_methods(["POST"])
def create_digital_sign_order_daily_paper(request):
    datasource: dict[str, any] = json.loads(request.body)
    formInstanceId = datasource["formInstanceId"]
    report_code = datasource["report_code"]
    participants_p = datasource["participants_p"]
    model_uuid = datasource["model_uuid"]
    report_model = YidaClient.get_form_data_by_search_field(
        "FORM-D4C9AA2AA5634D7CB46142B94F6B8441IA1U", admin_user_id, {"textField_lq966fhr": model_uuid})
    participants_personal = []
        # 公章区域数据列表
    official_seal_area_list = []
    if report_model:
        sign_areas = report_model[0].form_data['tableField_ls9optr6']
        for index, sign_area in enumerate(sign_areas):
            if len(participants_p) <= index:
                continue
        #个人章
            participants_personal.append({
                "userType": "2",
                "dingtalkUserId": participants_p[index],
                "coordinate": rf"[{{lby:{centimeter_transformation_point(sign_area['numberField_ls9optra'])},lbx:{centimeter_transformation_point(sign_area['numberField_ls9optr9'])},rty:{centimeter_transformation_point(sign_area['numberField_ls9optra']) + centimeter_transformation_point(sign_area['numberField_ls9optro'])},rtx:{centimeter_transformation_point(sign_area['numberField_ls9optr9']) + centimeter_transformation_point(sign_area['numberField_ls9optro'])},page:{sign_area['numberField_ls9optr7']}}}]"
            })
        
        # # 公章区域 ------------
        official_seal_areas = report_model[0].form_data['tableField_lt8ndw9l']
        for index, official_seal_area in enumerate(official_seal_areas):
            seal = json.loads(json.loads(official_seal_area.get("associationFormField_lvdgd8ot_id")))[0]
            matching_items = [item for item in official_seal_area_list if item.get("sealFileUuid") == seal.get("subTitle")]
            if matching_items:
                official_coordinate = matching_items[0].get("coordinate_list")
            else:
                official_seal_info = {
                    "userType": "2",
                    "dingtalkUserId": report_model[0].form_data['employeeField_lv5hk4vg_id'][0],
                    "sealFileUuid": seal.get("subTitle"),
                    "coordinate":"",
                    "coordinate_list":[],
                    "enterpriseCardno":"93k12jadfas01231203",
                    "coordinateRiding":f"{centimeter_transformation_point(official_seal_area['numberField_ls9optrm'])}F,{centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m'])}F" if official_seal_area.get("numberField_ls9optrm") else None
                }
                official_seal_area_list.append(official_seal_info)
                official_coordinate = official_seal_info.get("coordinate_list")
            coordinate_item = {
                'lbx': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9o']),
                'lby': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9n']),
                'rtx': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9o']) + centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m']),
                'rty': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9n']) + centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m']),
                'page': official_seal_area['numberField_lt8ndw9p']
            }
            official_coordinate.append(coordinate_item)
        for seal_e in official_seal_area_list:
            seal_e["coordinate"] = json.dumps(seal_e["coordinate_list"])       
        # 公章区域 ------------
    url = f'https://api.zjcxjc.cn/api/v1/digital-sign/create-order'
    data = {
        "participants": [],
        "callbackUrl":"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/sign_order_completed_daily_paper"
    }
    data["participants"].extend(participants_personal)
    data["participants"].extend(official_seal_area_list)
    print('participants-->',data["participants"])
    response = requests.post(url, json=data)
    
    daily_paper = YidaClient.get_form_items_by_ids(
        "FORM-861219708B7A49A7B9BA2A25A53965ACYDQU",
        formInstanceId,
        admin_user_id
    )
    print(daily_paper[0].form_data['attachmentField_lvkjxzeg'])
    # return ApiResponse.success(message="订单创建成功")
    url = json.loads(daily_paper[0].form_data['attachmentField_lvkjxzeg'])[0]['url']
    # https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202405/4cf46c79-7a9a-419d-b742-bbfea57dda02/origin.pdf
    parts = url.split("download_file/")
    if len(parts) > 1:
        wholePDF_ossUrl = parts[1]
        print(wholePDF_ossUrl)  # 输出：out-pdf/202405/4cf46c79-7a9a-419d-b742-bbfea57dda02/origin.pdf
    else:
        print("未找到该报告的oss路径")   
    print(data["participants"]) 
    
    # return ApiResponse.success(message="订单创建成功")
    if response.status_code == 200:
        res = response.json()
        # print(res)
        if (res["code"] == 200):
            for item in data["participants"]:
                # print(item["dingtalkUserId"])
                YidaClient.create_form_data(
                    "FORM-6ABF70417C36461B94DCF647572F84B67EAC",
                    admin_user_id,
                    {
                        "textField_ls0gkw31": report_code,
                        "textField_lrzglud2": res["data"]["orderNum"],
                        "textField_lrzglud3": item["dingtalkUserId"],
                        "employeeField_ls0fsd2m": [item["dingtalkUserId"]],
                        "selectField_ls0fsd2n": "个人"
                    }
                )
            YidaClient.update_form_data_by_id(
                "FORM-861219708B7A49A7B9BA2A25A53965ACYDQU",
                admin_user_id, 
                formInstanceId,
                {
                    # 订单编号添加到日报流程表中
                    "textField_lvuq4bsd":res["data"]["orderNum"]
                }
            )
            print("url---",res['data']['contractFilePath'])
            digital_bucket.copy_object(
                "xu-bk-chengxiang", wholePDF_ossUrl, res['data']['contractFilePath']+'origin.pdf')
            ds_no = res["data"]["orderNum"]
            print('-',ds_no)
            return ApiResponse.success(message="订单创建成功", data=ds_no)
        return ApiResponse.fail(message="订单创建失败>>>")
    else:
        # 处理错误情况
        return ApiResponse.fail(message="订单创建失败")